/**
 * desc: 快递打印弹框页面
 */

import React, { useState, useEffect, useCallback } from "react";
import { CommonModal } from "@/views/components/CommonModal";
import { Select, Form, Modal, Popover } from "antd";
import {
	checkComponentsIsOpen,
	getAllPrinter,
	judgeHasWhichPlatform,
	print,
	printCheckList,
	printVipShop
} from "@/utils/print.jsx";
import { cloneDeep, find, isEmpty } from "lodash";
import { getPrinterName, getExpressRelativePrinter, setExpressRelativePrinter } from "@/utils/authority";
import moment from "moment";
import { cashpaymentPrint } from "../service";
import { queryDouYinPrintParam } from "@/services/common";
const { Option } = Select;

//缓存多次提交打印数据的队列
const stagePrintData = [];

const layout1 = {
	//发布表单排布
	labelCol: {
		span: 8
	},
	wrapperCol: {
		span: 14
	}
};

const updatePrintTime = async params => {
	return new Promise((resolve, reject) => {
		resolve({});
	});
};
const updatePrinterName = async params => {
	return new Promise((resolve, reject) => {
		resolve({});
	});
};
/**
 * pageData : records
 * ids
 * onOk
 * onCancel
 */
export default props => {
	const { selectedRows, handleCancel } = props;
	const ids = selectedRows.map(item => item.id);
	const pageData = selectedRows;
	const isAllPackages = false;
	const onOk = () => {};

	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);

	//打印机列表
	const [data, setData] = useState([]);

	const [configObj, setConfigObj] = useState({});

	// 当前获取的面单数据列表
	const [currentGetData, setCurrentGetData] = useState([]);

	// 当前打印的面单数据列表
	const [orderList, setOrderList] = useState([]);

	useEffect(() => {
		//获取打印机列表
		getAllPrinter(value => setData(value));
	}, []);

	useEffect(() => {
		if (data.length) {
			//开始查询打印数据
			getData();
		}
	}, [data]);

	const getLogisticsCompany = useCallback(
		logisticsNo => {
			const f = selectedRows.find(e => e.waybillNo == logisticsNo);
			return f?.expressCompany || "未找到快递公司";
		},
		[selectedRows]
	);
	// 获取面单号
	const getData = async () => {
		setLoading(true);
		const selectData = pageData.filter(item => item.logisticsJobType != 13), //列表选中的行数据 (手动修改物流信息的跳过)
			// selectData.reduce((prev,next)=>[...prev, next.orderSn], [])
			omsOrderSns = [];
		ids.map(item => {
			const obj = find(selectData, ["id", item]);
			if (obj) {
				omsOrderSns.push(obj.orderSn);
			}
		});

		const param = selectedRows.map(e => e.outboundNo);
		const { data, success } = await cashpaymentPrint({ takeGoodList: selectedRows });
		if (success && data?.length) {
			const obj = getExpressRelativePrinter();
			const originSetName = getPrinterName();
			const newConfig = {};
			//按照主页列表新排序 newPrintList 打印时实际遍历对象
			const newPrintList = data.codeTemplate.map(item => {
				const logisticsCompany = getLogisticsCompany(item);
				newConfig[logisticsCompany] = obj ? judgePrinterIsOnline(obj[logisticsCompany]) : judgePrinterIsOnline(originSetName);
				return {
					...item,
					id: item.orderSn + Math.random(),
					logisticsCompany
				};
			});
			setConfigObj(newConfig);
			setCurrentGetData(data);
		} else {
			setCurrentGetData([]);
		}
		setLoading(false);
	};

	//判断配置的打印机是否在线
	const judgePrinterIsOnline = name => {
		if (data.includes(name)) {
			return name;
		} else {
			return null;
		}
	};

	useEffect(() => {
		form.setFieldsValue(configObj);
	}, [configObj]);

	useEffect(() => {
		if (orderList.length) {
			currentGetData.length && setCurrentGetData([]);
			handleReduceSubmit(0);
		}
	}, [orderList]);

	//点击打印
	const handleOk = () => {
		form.validateFields();
		if (Object.keys(configObj).length) {
			const isSelect = [],
				notSelect = [];
			Object.keys(configObj).map(item => {
				if (configObj[item]) {
					isSelect.push(item);
				} else {
					notSelect.push(item);
				}
			});
			if (notSelect.length) {
				const newConfig = {};
				[...notSelect, ...isSelect].map(item => (newConfig[item] = configObj[item]));
				setConfigObj(newConfig);
				return Modal.info({
					centered: true,
					content: (
						<div>
							检测到【<span style={{ fontWeight: "bold" }}>{notSelect.join("，")}</span>
							】未设置对应打印机，为了不影响快递打印，请设置对应快递的打印机
						</div>
					)
				});
			}
			setLoading(true);
			const useCheckedarr = [];
			currentGetData.map(item => {
				useCheckedarr.push(item);
			});
			checkComponentsIsOpen(judgeHasWhichPlatform(useCheckedarr), res => {
				if (res.status) {
					//锁定打印机 任务id
					let getNums = 0;
					const postParams = []; //更新打印机名称（打印批次）
					currentGetData.map((item, index) => {
						postParams.push({ taskId: item.id, printerName: configObj[item.logisticsCompany] });

						getNums++;
						const printGroup = [{ ...item, taskId: item.id, printerName: configObj[item.logisticsCompany] }];
						if (!index && !orderList.length) {
							setOrderList(cloneDeep(printGroup));
						} else {
							stagePrintData.push(printGroup);
						}
					});
					updatePrinterName(postParams);
					//更新本地存储配置信息
					const obj = getExpressRelativePrinter() || {};
					setExpressRelativePrinter({
						...obj,
						...configObj
					});

					Modal.success({
						content: isAllPackages
							? `面单打印完成,总计${useCheckedarr.length}个,成功${getNums}个,失败${useCheckedarr.length - getNums}个`
							: `面单打印完成,总计${ids.length}个,成功${getNums}个,失败${ids.length - getNums}个`,
						onOk: () => {
							onOk();
						}
					});
				}
				setLoading(false);
			});
		} else if (data.codeTemplate) {
			Modal.info({ centered: true, content: "未监测到可打印的数据" });
		}
	};

	const handleReduceSubmit = num => {
		const promise = new Promise(async resolve => {
			const list = orderList[num];
			if (isEmpty(list)) {
				resolve();
				return;
			}
			if (list.platform == 0) {
				const printData = JSON.parse(list.printData);
				printCheckList(
					printData,
					() => {
						handleReduceSubmit(num + 1);
					},
					printData.printName
				);
				return;
			}
			if (list.platform == 2 || list.platform == 28) {
				//拼多多
				const data = {
					ERPId: 303379400,
					cmd: "print",
					requestID: list.orderSn + moment().valueOf(),
					task: {
						documents: [
							{
								contents: [JSON.parse(list.printData), { ...list.customData }],
								documentID: list.orderSn
							}
						],
						notifyType: ["print"],
						preview: false,
						previewType: "image",
						printer: list.printerName,
						taskID: list.orderSn + moment().valueOf(),
						firstDocumentNumber: num + 1,
						totalDocumentCount: orderList.length
					},
					version: "1.0"
				};
				print(1, data, async res => {
					if (res.status) {
						await updatePrintTime({ ids: list.orderId });
						// len --;
					}
					handleReduceSubmit(num + 1);
				});
			} else if (list.platform == 6 || list.platform == 29) {
				const printObj = JSON.parse(list.printData);
				const data = {
					orderType: "print",
					dataType: printObj.dataType,
					parameters: {
						printName: list.printerName,
						addData: printObj.addData,
						tempUrl: printObj.tempUrl,
						customTempUrl: list.customData.templateURL,
						customData: [list.customData.data],
						printData: [printObj.data]
					}
				};
				print(6, data, async res => {
					if (res.status) {
						await updatePrintTime({ ids: list.orderId });
						// len --;
					}
					handleReduceSubmit(num + 1);
				});
			} else if (list.platform == 7) {
				printVipShop(
					list.printData,
					async res => {
						if (res.status) {
							await updatePrintTime({ ids: list.orderId });
							// len --;
						}
						handleReduceSubmit(num + 1);
					},
					list.printerName
				);
			} else if (list.platform == 8) {
				const printObj = JSON.parse(list.printData);
				const data = {
					actionType: "PRINT",
					traceId: +new Date(),
					storeId: printObj.storeId,
					printerName: list.printerName,
					printParamDTO: {
						templateUrl: printObj.tempUrl,
						printDatas: [printObj],
						// "senderData": list.senderData,
						customData: list.customData
					}
				};
				print(8, data, async res => {
					if (res.status) {
						await updatePrintTime({ ids: list.orderId });
						// len --;
					}
					handleReduceSubmit(num + 1);
				});
			} else if (list.platform == 14) {
				//快手
				const printObj = JSON.parse(list.printData);
				const data = {
					cmd: "print",
					requestID: list.orderSn + moment().valueOf(),
					version: "1.0",
					task: {
						taskID: list.orderSn + moment().valueOf(),
						preview: false,
						printer: list.printerName,
						previewType: "pdf",
						firstDocumentNumber: num + 1,
						totalDocumentCount: orderList.length,
						documents: [
							{
								documentID: list.orderSn,
								contents: [
									{
										addData: printObj.addData,
										encryptedData: printObj.printData,
										signature: printObj.signature,
										key: printObj.key,
										templateURL: printObj.templateURL,
										ver: "waybill_print_secret_version_1"
									},
									{
										customData: list?.customData?.data,
										templateURL: list?.customData?.templateURL
									}
								]
							}
						]
					}
				};
				print(14, data, async res => {
					if (res.status) {
						await updatePrintTime({ ids: list.orderId });
						// len --;
					}
					handleReduceSubmit(num + 1);
				});
			} else if (list.platform == 15) {
				// 抖音
				const dyRes = await queryDouYinPrintParam({ orderCode: list.orderSn });
				const { success, data } = dyRes;
				let newData = {};
				newData.signature = JSON.parse(list.printData).sign;
				newData.templateURL = JSON.parse(list.printData).templateURL;
				newData.params = data;
				newData.encryptedData = JSON.parse(list.printData).print_data;
				newData.addData = JSON.parse(list.printData).addData;
				if (success) {
					const data1 = {
						cmd: "print",
						requestID: list.orderSn + moment().valueOf(),
						version: "1.0.1.8",
						task: {
							taskID: list.orderSn + moment().valueOf(),
							firstDocumentNumber: num + 1,
							totalDocumentCount: orderList.length,
							preview: false,
							printer: list.printerName,
							previewType: "pdf",
							documents: [
								{
									documentID: list.orderSn,
									contents: [newData, { ...list.customData }]
								}
							]
						}
					};
					print(15, data1, async res => {
						if (res.status) {
							await updatePrintTime({ ids: list.orderId });
							// len --;
						}
						handleReduceSubmit(num + 1);
					});
				}
			} else if (list.platform == 25) {
				const printObj = JSON.parse(list.printData);
				const data = {
					command: "print",
					version: "2.0",
					requestID: list.orderSn + Date.now(),
					printer: list.printerName,
					taskList: [
						{
							taskID: list.orderSn + Date.now(),
							printInfo: printObj.printData,
							printNum: {
								curNum: num + 1,
								sumNum: orderList.length
							},
							customInfo: { templateUrl: list?.customData?.templateURL, data: list?.customData?.data },
							extendData: { ...printObj.addData }
						}
					]
				};
				print(25, data, async res => {
					if (res.status) {
						await updatePrintTime({ ids: list.orderId });
						// len --;
					}
					handleReduceSubmit(num + 1);
				});
			} else if (list.platform == 33) {
				//得物
				const printObj = JSON.parse(list.printData);
				const data = {
					cmd: "print",
					version: "2.2.1",
					requestID: list.orderSn + Date.now(),
					task: {
						isvName: "isvName", // ISV 名称
						taskID: list.orderSn + Date.now(),
						printer: list.printerName,
						firstDocumentNumber: num + 1,
						totalDocumentCount: orderList.length,
						documents: [
							{
								printData: { ...printObj, customContent: undefined },
								customContent: printObj.customContent
							}
						]
					}
				};
				print(33, data, async res => {
					if (res.status) {
						await updatePrintTime({ ids: list.orderId });
						// len --;
					}
					handleReduceSubmit(num + 1);
				});
			} else if (list.platform == 40) {
				//小红书
				const data = {
					cmd: "print",
					requestID: list.orderSn + moment().valueOf(),
					version: "1.0",
					task: {
						taskID: list.orderSn + moment().valueOf(),
						preview: false,
						printer: list.printerName,
						previewType: "pdf",
						firstDocumentNumber: num + 1,
						totalDocumentCount: orderList.length,
						documents: [
							{
								documentID: list.orderSn,
								contents: [JSON.parse(list.printData), { ...list.customData }]
							}
						]
					}
				};
				print(40, data, async res => {
					if (res.status) {
						await updatePrintTime({ ids: list.orderId });
						// len --;
					}
					handleReduceSubmit(num + 1);
				});
			} else {
				let data;
				if (list.platform == 5) {
					//顺丰
					data = {
						cmd: "print",
						requestID: list.orderSn + moment().valueOf(),
						version: "1.0",
						task: {
							taskID: list.orderSn + moment().valueOf(),
							preview: false,
							printer: list.printerName,
							previewType: "pdf",
							firstDocumentNumber: num + 1,
							totalDocumentCount: orderList.length,
							documents: [
								{
									documentID: list.orderSn,
									contents: [JSON.parse(list.printData)]
								}
							]
						}
					};
				} else {
					data = {
						cmd: "print",
						requestID: list.orderSn + moment().valueOf(),
						version: "1.0",
						task: {
							taskID: list.orderSn + moment().valueOf(),
							preview: false,
							printer: list.printerName,
							previewType: "pdf",
							firstDocumentNumber: num + 1,
							totalDocumentCount: orderList.length,
							documents: [
								{
									documentID: list.orderSn,
									contents: [JSON.parse(list.printData), { ...list.customData }]
								}
							]
						}
					};
				}
				print(2, data, async res => {
					if (res.status) {
						await updatePrintTime({ ids: list.orderId });
						// len --;
					}
					handleReduceSubmit(num + 1);
				});
			}
		});

		promise.then(() => {
			if (stagePrintData.length) {
				setOrderList(stagePrintData[0]);
				stagePrintData.splice(0, 1);
			} else {
				setOrderList([]);

				handleCancel();
			}
		});
	};

	// 设置打印机名称
	const handlePrinterName = (key, name) => {
		setConfigObj({
			...configObj,
			[key]: name
		});
	};

	const options =
		!isEmpty(data) &&
		data.map(d => (
			<Option key={d} value={d}>
				{d}
			</Option>
		));

	const onCancel = () => {
		setConfigObj({});
		handleCancel();
	};

	return (
		<CommonModal title={{ title: "快递批量打印" }} open={true} onCancel={onCancel} width="500px" onOk={handleOk} okText="打印">
			<Form form={form} {...layout1} name="order-print-setexpress">
				<Form.Item label="可打印订单数量：" name="orderCount">
					<div style={{ fontWeight: "bold" }}>{ids.length}</div>
				</Form.Item>
				{Object.keys(configObj).length ? (
					Object.keys(configObj).map(item => (
						<Form.Item
							label={
								<Popover content={item}>
									<span className="textOverflowMultiOne">{item}</span>
								</Popover>
							}
							name={item}
							rules={[{ required: true, message: "请选择打印机" }]}
							key={item}
						>
							<Select allowClear placeholder="请选择打印机" onChange={e => handlePrinterName(item, e)} value={configObj[item]}>
								{options}
							</Select>
						</Form.Item>
					))
				) : (
					<div style={{ fontSize: "16px", marginTop: "38px", textAlign: "center" }}>
						{loading
							? "正在努力获取打印数据"
							: data.codeTemplate
								? "暂未获得物流信息，请检查运单号"
								: "未获取到打印机，将无法打印"}
					</div>
				)}
			</Form>
		</CommonModal>
	);
};
